"use strict"

var log 		= 	console.log,									//env variables
	http 		= 	require('http'),
	GET 		=	require("./php-get.js"),
	DB			=	require("./DB-storage.js"),
	cleaner 	= 	require("./game-cleaner.js"),
	CreateGame	= 	require("./create-game.js")

cleaner.start()														//start the game cleaner timer loop


var loc = "127.0.0.1", port = 1337
http.createServer(function (req, res) {								//main server loop
	req.content = ""
	req.addListener("data", function(chunk) {
		req.content += chunk
	})
	req.addListener("end", function() {
		handlePOST(req, res)
	})
}).listen(port, loc)


var handlePOST = function(req, res) {
	try {
		
		//set some crap to allow chrome to do CORS
		var responseHead = {
			'Content-Type': 'text/plain',
			'Access-Control-Allow-Origin': '*',
			"Access-Control-Allow-Credentials": "true",
			"Access-Control-Allow-Methods": "OPTIONS, GET, POST",
			"Access-Control-Allow-Headers": "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control"
		}
		var statusCode = 200, response = ""
		
		var cTime = new Date().getTime()								//current time of script execution. bound to be useful
		var data = GET.parse(req.content)								//turn the POST into an array of vars
		
		switch (data.type) {											//select by request type
			case "sendMove":											//save sent move
				//res.write(data.payload + "\n")
				
				//update game to keep the timestamp current
				var game = DB.retrieveGame(data.payload)
				DB.storeGame(game)

				DB.storeMove(data.payload)								//save it (error check this?)
				response += "sendMove: successfully received \n"		//all ok!
				break
				
			case "getMove":
				var move = DB.retrieveMove(data.payload)
				if (move === false) {									//false signifies no game exists
					statusCode = 204
					//response += "getMove: move could not be retrieved or does not exist \n"
				} else {
					response += move
				}
				break
				
			case "gamesList":
				var gamesList = DB.gamesList(data.gametype)
				response += JSON.stringify(gamesList)
				break
			
			
			case "checkGameStatus":
				//get game from the filesystem
				var game = DB.retrieveGame(data.payload)
				
				//force store to upate last access time
				DB.storeGame(game)
				
				//return current game state
				response += game
				break
			
			
			case "joinGame":
				var game = DB.retrieveGame(data.payload)				//retrieve game from filesystem
				if (game === false) {
					statusCode = 404
					response += "joinGame: game could not be retrieved or does not exist \n"
					break
				}
				
				game = JSON.parse(game)									//get the game and payload as json
				var json = JSON.parse(data.payload)
				if (game.players.length === 2) {						//only 2 players per game
					statusCode = 400
					response += "joinGame: game is already full \n"
					break
					
				} else if (game.players[0] === json.playerName) {		//players must have unique names
					statusCode = 400
					response += "joinGame: both opponents cannot have the same name \n"
					break
				}
				
				game.players.push(json.playerName)						//add player to game
				game.lastUpdated = cTime
				game = JSON.stringify(game)
				DB.storeGame(game)
				
				response += game										//return game details to player
				break
			
			case "createGame":
				var game = JSON.parse(data.payload)
				
				// create the game
				var newGame = CreateGame.create(data.gametype, game.playerName)
				
				// save the new game
				var newGameStr = JSON.stringify(newGame)
				DB.storeGame(newGameStr)
				
				// log what we did
				//log("created game: " + newGameStr)
				log("created game. ID: '" + newGame.gameId + "', Type: '" + data.gametype + "'")
				
				// return it in the response
				response += newGameStr
				break
					
			default:
				statusCode = 400										//Bad Request
				response += "'type' was not recognised \n"
		}
		
		res.writeHead(statusCode, responseHead)
		if (response)  res.write(response)
	
		//res.write(JSON.stringify(data) + "\n")
		//res.write(req.method + "\n") //check method?
		
		res.end()
	
	} catch(e) {
		log("handlePOST encountered error: " + e)
	}
}


log('Server running at http://' + loc + ':' + port + '/')
